"""
    TorrentBrowser plugin for XBMC
    Copyright (C) 2011-2012 Markus Langenoja
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
    Function [TBTools]
    ------------------
    * sumInfo2Xbmc() - Puts together a dictionary with information to scrape
    * getUserInput(title) - Show XBMC keyboard for input with a title
    * getParams(parameterString) - Extract commands from XBMC-parameters
    * replaceBadSign(string) - Replaces HTML codes in string to readable signs
    * showNotification(header,message,duration) - Shows a XBMC notification
    * showOK(header,message) - Show OK dialog
    * stripTitle(string) - Tries to extract Title and Year from string
    * cleanString(string) - Cleans string to be save-friendly
"""        
import xbmc, xbmcgui
import sys, string, re

class TBTools:
    __settings__ = sys.modules[ "__main__" ].__settings__
    __deb__ = sys.modules[ "__main__" ].__deb__
    __plugin__ = sys.modules[ "__main__" ].__plugin__
    
    # Modify this to remove stuff from title such as DVDRiP etc.
    stripRegExp = '^(.+?)[\s.](LIMITED|LiMiTeD|EXTENDED|DVD|R5|DVDRip|REPACK|BR|720|1080|UNRATED|BDRip|PROPER)'
    if __deb__:
        print __plugin__ + '::DEBUG::TBTools::' + 'Initiation:: Stripping regExp for titles %s' % (stripRegExp)
    
    # KEYBOARD FOR SEARCHES
    def getUserInput(self, title="Input", default="", hidden=False):
        result = None
        
        keyboard = xbmc.Keyboard(default, title)
        keyboard.setHiddenInput(hidden)
        keyboard.doModal()
        
        if keyboard.isConfirmed():
            result = keyboard.getText()
            result = result.replace(' ','%20')
            
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBTools::' + 'getUserInput:: User input \'%s\'' % (result)
            
        return result
        
    # NOTIFICATION
    def showNotification(self,header,message,duration):
        duration = duration*1000
        command = 'Notification(%s,%s,%s)' % (header,message,duration)
        xbmc.executebuiltin(command)
        
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBTools::' + 'showNotification:: Header: %s Message: %s Duration: %s' % (header,message,duration)
            
    # OK Dialog
    def showOK(self,header,message):
        dialog = xbmcgui.Dialog()
        if type(message) == list:
            length = len(message)
            if length == 3:
                ok = dialog.ok(header,message[0],message[1],message[2])
            elif length == 2:
                ok = dialog.ok(header,message[0],message[1])
            else:
                ok = dialog.ok(header,message[0])
        else:   
            ok = dialog.ok(header,message)
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBTools::' + 'showOK:: Header: %s Message: %s' % (header,message)
            
        return ok
    
    # PARAMETER CONVERSION
    def getParams(self, parameterString):
        commands = {}
        splitCommands = parameterString[parameterString.find('?')+1:].split('&')
        
        for command in splitCommands:
            if (len(command) > 0):
                splitCommand = command.split('=')
            key = splitCommand[0]
            value = splitCommand[1]
            commands[key] = value
            
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBTools::' + 'getParams:: Extracted commands %s' % (commands)
            
        return commands
    
    # REPLACES BAD SIGN FROM HTML
    def replaceBadSigns(self,string):	
        string = string.strip()		
        string = string.replace('&amp;','&')
        string = string.replace("&quot;", '"')
        string = string.replace("&hellip;", "...")
        string = string.replace("&gt;",">")
        string = string.replace("&lt;","<")
        string = string.replace("&#39;","'")
        return string
    
    def stripTitle(self,title):
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBTools::' + 'stripTitle:: Before: %s' % (title)
        year = []
        if re.search('\[REQ',title):
            title = re.compile('\[REQ\] (.+?)$').findall(title)[0]
        if re.search('[.\s(](\d\d\d\d)[.\s)]',title):
            year = re.compile('(\d\d\d\d)').findall(title)[0]
        if re.search('(.+?)\(',title):
            title = re.compile('(.+?)\(').findall(title)[0]
        if re.search('(.+?)\d\d\d\d',title):
            title = re.compile('(.+?)\d\d\d\d').findall(title)[0]
        if re.search(self.stripRegExp,title):
            title = re.compile(self.stripRegExp).findall(title)[0][0]
        if re.search('(.+?)S\d\d.*',title):
            title = re.compile('(.+?)S\d\d.*').findall(title)[0]
        
        title = title.replace('.',' ')
        title = title.replace(',','')
        title = title.replace(':','')
        title = title.replace('\'','')
        if re.search('\s+', title):
            title = re.sub('\s+',' ',title)
        if re.search('(.+?)\s$',title):
            title = re.compile('(.+?)\s$').findall(title)[0]
            
        if self.__deb__:
            print self.__plugin__ + '::DEBUG::TBTools::' + 'stripTitle:: After: %s' % (title)
            
        if year:
            return title, year
        else:
            return title
    
    def cleanString(self,inStr):
        validCharacters = '-_.() %s%s' % (string.ascii_letters, string.digits)
        cleanedString = ''.join(i for i in inStr if i in validCharacters)
        return cleanedString